package cn.jaye.fabric.common.aspect;

import cn.jaye.fabric.common.constant.Global;
import com.alibaba.fastjson.JSON;
import cn.jaye.fabric.common.model.BaseCommand;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Jaye on 2017/10/18.
 */
@Aspect
@Order(-2)
@Component
public class GlobalRequestAspect {

    private final static Logger logger = LoggerFactory.getLogger(GlobalRequestAspect.class);

    @Value("${spring.application.name}")
    private String applicationName;

    @Pointcut("execution(public * cn.jaye.fabric.controller.*.*(..))")
    public void log() {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(Global.LOG_PARA_SERVICE_NAME + ":" + applicationName);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        stringBuffer.append(" "+df.format(new Date()));
        stringBuffer.append(" " + Global.LOG_PARA_URL + ":" + request.getRequestURI());
        Object[] objects = joinPoint.getArgs();
        for (Object object : objects) {
            if (object instanceof BaseCommand) {
                stringBuffer.append(" " + Global.LOG_PARA_PARAS + ":" + JSON.toJSONString(object));
            }
        }
        logger.info(stringBuffer.toString());
    }
    @AfterReturning(pointcut = "log()", returning = "object")//打印输出结果
    public void doAfterReturing(Object object) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(Global.LOG_PARA_SERVICE_NAME + ":" + applicationName);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        stringBuffer.append(" "+df.format(new Date()));
        stringBuffer.append(" " + Global.LOG_PARA_RESPONSE + ":" + JSON.toJSONString(object));
        logger.info(stringBuffer.toString());
    }
}
